package com.lm.scau.framedemos.Utils;

import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Created by huanbin Chen on 2015/9/16 17:16
 */
public class DateUtils {

    private static Calendar calendar;
    private static final String TAG = DateUtils.class.getSimpleName();
    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT = "yyyy-MM-dd";

    /**
     * 年
     **/
    public static int getYear() {
        calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 月,calendar month从0开始
     **/
    public static int getMonth() {
        calendar = Calendar.getInstance();
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 日
     **/
    public static int getDay() {
        calendar = Calendar.getInstance();
        return calendar.get(Calendar.DATE);
    }

    /**
     * 24小时制的小时
     **/
    public static int getHourOfDay() {
        calendar = Calendar.getInstance();
        return calendar.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 12小时制的小时
     **/
    public static int getHour() {
        calendar = Calendar.getInstance();
        return calendar.get(Calendar.HOUR);
    }

    /**
     * 分钟
     **/
    public static int getMinute() {
        calendar = Calendar.getInstance();
        return calendar.get(Calendar.MINUTE);
    }

    /**
     * 秒钟
     **/
    public static int getSecond() {
        calendar = Calendar.getInstance();
        return calendar.get(Calendar.SECOND);
    }

    /**
     * getTime:获取时间
     */
    public static String getTime(Date date) {
        TimeZone t = TimeZone.getTimeZone("GMT+08:00");// 获取东8区TimeZone
        Calendar calendar = Calendar.getInstance(t);
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int min = calendar.get(Calendar.MINUTE);
        int ss = calendar.get(Calendar.SECOND);
        return year + "-" + (month < 10 ? "0" : "") + month + '-' + (day < 10 ? "0" : "") + day + ' '
                + (hour < 10 ? "0" : "") + hour + ':' + (min < 10 ? "0" : "") + min + ":"
                + (ss < 10 ? "0" : "") + ss;
    }

    /**
     * getDate: 获取日期
     */
    public static String getDate() {
        TimeZone t = TimeZone.getTimeZone("GMT+08:00");// 获取东8区TimeZone
        Calendar calendar = Calendar.getInstance(t);
        calendar.setTimeInMillis(System.currentTimeMillis());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        return year + "-" + (month < 10 ? "0" : "") + month + '-' + (day < 10 ? "0" : "") + day;
    }

    public static int[] date(String str) {
        int year = 0;
        int month = 0;
        int day = 0;
        int pos = 4;
        int p = str.indexOf(" ");
        if (p == 9 || p == 8) {
            str = str.substring(0, p);
        }
        if (str.length() == 10 && str.substring(pos, pos + 1).equals("-")
                && str.substring(pos + 3, pos + 4).equals("-")) {
            int temp = Integer.parseInt(str.substring(0, pos));
            if (temp > 0) {
                year = temp;
                // System.out.println("year=="+year);
            }
            temp = Integer.parseInt(str.substring(pos + 1, pos + 3));
            if (temp > 0 && temp <= 12) {
                month = temp;
                // System.out.println("month=="+month);
            }
            temp = Integer.parseInt(str.substring(pos + 4, pos + 6));
            if (temp > 0 && temp <= 31) {
                day = temp;
                // System.out.println("day=="+day);
            }
        } else if (str.length() == 9 && str.substring(pos, pos + 1).equals("-")
                && str.substring(pos + 2, pos + 3).equals("-")) {
            int temp = Integer.parseInt(str.substring(0, pos));
            if (temp > 0) {
                year = temp;
                // System.out.println("year=="+year);
            }
            temp = Integer.parseInt("0" + str.substring(pos + 1, pos + 2));
            if (temp > 0 && temp <= 9) {
                month = temp;
                // System.out.println("month=="+month);
            }
            temp = Integer.parseInt(str.substring(pos + 3, pos + 5));
            if (temp > 0 && temp <= 31) {
                day = temp;
                // System.out.println("day=="+day);
            }
        } else if (str.length() == 9 && str.substring(pos, pos + 1).equals("-")
                && str.substring(pos + 3, pos + 4).equals("-")) {
            int temp = Integer.parseInt(str.substring(0, pos));
            if (temp > 0) {
                year = temp;
                // System.out.println("year=="+year);
            }
            temp = Integer.parseInt(str.substring(pos + 1, pos + 3));
            if (temp > 0 && temp <= 12) {
                month = temp;
                // System.out.println("month=="+month);
            }
            temp = Integer.parseInt(str.substring(pos + 4, pos + 5));
            if (temp > 0 && temp <= 9) {
                day = temp;
                // System.out.println("day=="+day);
            }
        } else if (str.length() == 8 && str.substring(pos, pos + 1).equals("-")
                && str.substring(pos + 2, pos + 3).equals("-")) {
            int temp = Integer.parseInt(str.substring(0, pos));
            if (temp > 0) {
                year = temp;
                // System.out.println("year=="+year);
            }
            temp = Integer.parseInt("0" + str.substring(pos + 1, pos + 2));
            if (temp > 0 && temp <= 9) {
                month = temp;
                // System.out.println("month=="+month);
            }
            temp = Integer.parseInt(str.substring(pos + 3, pos + 4));
            if (temp > 0 && temp <= 9) {
                day = temp;
                // System.out.println("day=="+day);
            }
        }
        return new int[]{year, month, day};
    }

    /**
     * String 转为Date
     * @param str 日期
     * @param pattern 格式 例如：DateUtils.DATE_FORMAT
     * @return
     */
    public static Date String2Date(String str, String pattern) {
        try {
            SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
            return format.parse(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 解析日期表达式，形如day(2),month(-2,0)
     * match不能为空串！！！
     * 如果没有def默认值，则根据match确定时间段还是时间
     * def为空，默认展开的时候是当天
     *
     * @return String[] 字符串格式为yyyy-MM-dd(如果存在m,d)
     **/
    public static String[] parseDateTimeDefStrArray(String match, String def, String unit) {
        if (def.contains(",") || def.equals("") && match.contains(",")) {//时间段
            return parseTimeDefStrArray(def, unit);
        } else {//match为时间点，def为空或者时间点
            return parseDateDefStrArray(def);
        }
    }

    private static String[] parseTimeDefStrArray(String def, String unit) {
        if (StringUtil.isNotBlank(unit)) {
            String iUnit;
            if (unit.contains("|")) {
                iUnit = unit.split("\\|")[0].trim();
            } else {
                iUnit = unit;
            }
            List<int[]> yearMonthDay = parseDateTimeIntArrays(def);
            if (yearMonthDay == null || yearMonthDay.size() == 0) {
                return null;
            }
            String[] date = new String[2];
            for (int j = 0; j < yearMonthDay.size(); j++) {
                int[] defaultValue = yearMonthDay.get(j);
                StringBuilder builder = new StringBuilder();
                builder.append(defaultValue[0]);//year 一定存在
                for (int i = 1, s = defaultValue.length; i < s; i++) {//从1开始，因为年不可能为-1
                    if (defaultValue[i] == -1) {//没有的数值，设置为1
                        if (i == 1 && j == 1){//月份,且是第二个日期
                            defaultValue[i] = 12;
                        } else if (i == 2 && j == 1){//日，且是第二个日期
                            defaultValue[i] = getLastDayOfMonth(defaultValue[0],defaultValue[1]);
                        } else {
                            defaultValue[i] = 1;
                        }
                    }
                    builder.append("-");
                    builder.append(defaultValue[i]);
                }
                String sDate = builder.toString();
                switch (iUnit) {
                    case "day"://yyyy-mm-dd
                        date[j] = StringPattern(sDate, "y-M-d", "yyyy-MM-dd");
                        break;
                    case "month"://yyyy-mm
                        date[j] = StringPattern(sDate, "y-M-d", "yyyy-MM");
                        break;
                    case "year"://yyyy
                        date[j] = StringPattern(sDate, "y-M-d", "yyyy");
                        break;
                    default:
                        Log.w("parseDate in DateUtils", "can not find unit " + iUnit);
                        break;
                }
            }
            if (yearMonthDay.size() == 1) {
                date[1] = date[0];
            }
            return date;
        }
        return null;
    }

    private static String[] parseDateDefStrArray(String def) {
        if (def.contains("year")) {
            return parseYearDef(def);
        } else if (def.contains("month")) {
            return parseMonthDef(def);
        } else {
            return parseDayDef(def);
        }
    }

    /**
     * 解析年
     **/
    public static String[] parseYearDef(String def) {
        Calendar cal = Calendar.getInstance();
        // 当前年
        int y = cal.get(Calendar.YEAR);
        String[] texts = null;
        if (def == null || def.equals("")) {
            texts = new String[1];
            texts[0] = StringPattern(String.valueOf(y), "y", "yyyy");
        } else if (def.contains("year") && !def.contains(",")) {//month(0)
            texts = new String[1];
            int[] dayMonthYear = getYearRelative(Integer.valueOf(def.substring(5, def.indexOf(")"))));
            texts[0] = StringPattern(String.valueOf(dayMonthYear[0]), "y", "yyyy");
        } else if ((def.contains("year") && def.contains(","))) {
            texts = new String[2];
            int[] dayMonthYear1 = getYearRelative(Integer.valueOf(def.substring(5, def.indexOf(","))));
            texts[0] = StringPattern(String.valueOf(dayMonthYear1[0]), "y", "yyyy");
            int[] dayMonthYear2 = getYearRelative(Integer.valueOf(def.substring(def.indexOf(",") + 1, def.indexOf(")"))));
            texts[1] = StringPattern(String.valueOf(dayMonthYear2[0]), "y", "yyyy");
        }
        return texts;
    }

    /**
     * 解析月
     **/
    public static String[] parseMonthDef(String def) {
        Calendar cal = Calendar.getInstance();
        // 当前年
        int y = cal.get(Calendar.YEAR);
        // 当前月
        int m = (cal.get(Calendar.MONTH)) + 1;//month从0开始
        String[] texts = null;
        if (def == null || def.equals("")) {
            texts = new String[1];
            texts[0] = StringPattern(y + "-" + m, "y-M", "yyyy-MM");
        } else if (def.contains("month") && !def.contains(",")) {//month(0)
            texts = new String[1];
            int[] yearMonthDay = getMonthOfYearRelative(Integer.valueOf(def.substring(6, def.indexOf(")"))));
            texts[0] = StringPattern(yearMonthDay[0] + "-" + yearMonthDay[1], "y-M", "yyyy-MM");
        } else if ((def.contains("month") && def.contains(","))) {
            texts = new String[2];
            int[] yearMonthDay1 = getMonthOfYearRelative(Integer.valueOf(def.substring(6, def.indexOf(","))));
            texts[0] = StringPattern(yearMonthDay1[0] + "-" + yearMonthDay1[1], "y-M", "yyyy-MM");
            int[] yearMonthDay2 = getMonthOfYearRelative(Integer.valueOf(def.substring(def.indexOf(",") + 1, def.indexOf(")"))));
            texts[1] = StringPattern(yearMonthDay2[0] + "-" + yearMonthDay2[1], "y-M", "yyyy-MM");
        }
        return texts;
    }

    /**
     * 解析天
     **/
    public static String[] parseDayDef(String def) {
        Calendar cal = Calendar.getInstance();
        // 当前年
        int y = cal.get(Calendar.YEAR);
        // 当前月
        int m = (cal.get(Calendar.MONTH)) + 1;
        // 当前月的第几天：即当前日
        int d = cal.get(Calendar.DATE);
        String[] texts = null;
        if (def == null || def.equals("")) {
            texts = new String[1];
            texts[0] = StringPattern(y + "-" + m + "-" + d, "y-M-d", "yyyy-MM-dd");
        } else if (def.contains("day") && !def.contains(",")) {//day(0)
            int[] yearMonthDay = getDayOfMonthYearRelative(Integer.valueOf(def.substring(4, def.indexOf(")"))));
            texts = new String[1];
            texts[0] = StringPattern(yearMonthDay[0] + "-" + yearMonthDay[1] + "-" + yearMonthDay[2], "y-M-d", "yyyy-MM-dd");
        } else if ((def.contains("day") && def.contains(","))) {
            texts = new String[2];
            int[] yearMonthDay1 = getDayOfMonthYearRelative(Integer.valueOf(def.substring(4, def.indexOf(","))));
            texts[0] = StringPattern(yearMonthDay1[0] + "-" + yearMonthDay1[1] + "-" + yearMonthDay1[2], "y-M-d", "yyyy-MM-dd");
            int[] yearMonthDay2 = getDayOfMonthYearRelative(Integer.valueOf(def.substring(def.indexOf(",") + 1, def.indexOf(")"))));
            texts[1] = StringPattern(yearMonthDay2[0] + "-" + yearMonthDay2[1] + "-" + yearMonthDay2[2], "y-M-d", "yyyy-MM-dd");
        }
        return texts;
    }

    /**
     * 解析日期表达式，暂时只支持日、月、年。
     * 形如day(2),month(-2,0)，year(-2,2),如果为空串，则按照day的逻辑走（当天）
     *
     * @return List int[] ->{year,month,day}
     **/
    public static List<int[]> parseDateTimeIntArrays(String timeReg) {
        if (timeReg.contains("year")) {
            return parseYearIntArrays(timeReg);
        } else if (timeReg.contains("month")) {
            return parseMonthIntArrays(timeReg);
        } else {
            return parseDayIntArrays(timeReg);
        }
    }

    /**
     * 解析年
     **/
    public static List<int[]> parseYearIntArrays(String timeReg) {
        Calendar cal = Calendar.getInstance();
        // 当前年
        int y = cal.get(Calendar.YEAR);

        List<int[]> nums = new ArrayList<>();
        if (timeReg == null || timeReg.equals("")) {
            int[] num = new int[3];
            num[0] = y;
            num[1] = -1;
            num[2] = -1;//-1表示，数据不存在，后面搜索的时候需要进行解析
            nums.add(num);
        } else if (timeReg.contains(";")) {//year(-1;0;1),只能返回一串的时间了
            String relaticeDef = timeReg.replace("year(", "").replace(")", "");//变成-1;0;1的格式
            String[] timeRegs = relaticeDef.split(";");
            for (String s : timeRegs) {
                nums.addAll(parseYearIntArrays("year(" + s.trim() + ")"));
            }
            return nums;
        } else if (timeReg.contains("|")) {//year(-1)|year(0)|year(1),只能返回一串的时间了
            String[] timeRegs = timeReg.split("\\|");
            for (String s : timeRegs) {
                nums.addAll(parseDateTimeIntArrays(s.trim()));
            }
            return nums;
        } else if (timeReg.contains("year") && !timeReg.contains(",")) {
            int[] dayMonthYear = getYearRelative(Integer.valueOf(timeReg.substring(5, timeReg.indexOf(")"))));
            nums.add(dayMonthYear);
        } else if ((timeReg.contains("year") && timeReg.contains(","))) {
            int[] dayMonthYear1 = getYearRelative(Integer.valueOf(timeReg.substring(5, timeReg.indexOf(","))));
            int[] dayMonthYear2 = getYearRelative(Integer.valueOf(timeReg.substring(timeReg.indexOf(",") + 1, timeReg.indexOf(")"))));
            nums.add(dayMonthYear1);
            nums.add(dayMonthYear2);
        }
        return nums;
    }

    /**
     * 解析月
     **/
    public static List<int[]> parseMonthIntArrays(String timeReg) {
        Calendar cal = Calendar.getInstance();
        // 当前年
        int y = cal.get(Calendar.YEAR);
        // 当前月
        int m = (cal.get(Calendar.MONTH)) + 1;//month从0开始

        List<int[]> nums = new ArrayList<>();
        if (timeReg == null || timeReg.equals("")) {
            int[] num = new int[3];
            num[0] = y;
            num[1] = m;
            num[2] = -1;//这个表示，这是纯粹月份的，后面搜索的时候需要进行解析
            nums.add(num);
        } else if (timeReg.contains(";")) {//month(-1;0;1),只能返回一串的时间了
            String relaticeDef = timeReg.replace("month(", "").replace(")", "");//变成-1;0;1的格式
            String[] timeRegs = relaticeDef.split(";");
            for (String s : timeRegs) {
                nums.addAll(parseMonthIntArrays("month(" + s.trim() + ")"));
            }
            return nums;
        } else if (timeReg.contains("|")) {//month(-1)|month(0)|month(1),只能返回一串的时间了
            String[] timeRegs = timeReg.split("\\|");
            for (String s : timeRegs) {
                nums.addAll(parseDateTimeIntArrays(s.trim()));
            }
            return nums;
        } else if (timeReg.contains("month") && !timeReg.contains(",")) {//month(0)
            int[] yearMonthDay = getMonthOfYearRelative(Integer.valueOf(timeReg.substring(6, timeReg.indexOf(")"))));
            nums.add(yearMonthDay);
        } else if ((timeReg.contains("month") && timeReg.contains(","))) {
            int[] yearMonthDay1 = getMonthOfYearRelative(Integer.valueOf(timeReg.substring(6, timeReg.indexOf(","))));
            nums.add(yearMonthDay1);
            int[] yearMonthDay2 = getMonthOfYearRelative(Integer.valueOf(timeReg.substring(timeReg.indexOf(",") + 1, timeReg.indexOf(")"))));
            nums.add(yearMonthDay2);
        }
        return nums;
    }

    /**
     * 解析天,返回多个年月日的数组
     **/
    public static List<int[]> parseDayIntArrays(String timeReg) {
        Calendar cal = Calendar.getInstance();
        // 当前年
        int y = cal.get(Calendar.YEAR);
        // 当前月
        int m = (cal.get(Calendar.MONTH)) + 1;
        // 当前月的第几天：即当前日
        int d = cal.get(Calendar.DATE);
        List<int[]> nums = new ArrayList<>();
        if (timeReg == null || timeReg.equals("")) {
            int[] num = new int[3];
            num[0] = y;
            num[1] = m;
            num[2] = d;
            nums.add(num);
        } else if (timeReg.contains(";")) {//day(-1;0;1),只能返回一串的时间了
            String relaticeDef = timeReg.replace("day(", "").replace(")", "");//变成-1;0;1的格式
            String[] timeRegs = relaticeDef.split(";");
            for (String s : timeRegs) {
                nums.addAll(parseDayIntArrays("day(" + s.trim() + ")"));
            }
            return nums;
        } else if (timeReg.contains("|")) {//day(-1)|day(0)|day(1),只能返回一串的时间了。极端情况是day(0)|month(0)|year(0),暂时兼容
            String[] timeRegs = timeReg.split("\\|");
            for (String s : timeRegs) {
                nums.addAll(parseDateTimeIntArrays(s.trim()));
            }
            return nums;
        } else if (timeReg.contains("day") && !timeReg.contains(",")) {//day(0)
            int[] yearMonthDay = getDayOfMonthYearRelative(Integer.valueOf(timeReg.substring(4, timeReg.indexOf(")"))));
            nums.add(yearMonthDay);
        } else if ((timeReg.contains("day") && timeReg.contains(","))) {
            int[] yearMonthDay1 = getDayOfMonthYearRelative(Integer.valueOf(timeReg.substring(4, timeReg.indexOf(","))));
            nums.add(yearMonthDay1);
            int[] yearMonthDay2 = getDayOfMonthYearRelative(Integer.valueOf(timeReg.substring(timeReg.indexOf(",") + 1, timeReg.indexOf(")"))));
            nums.add(yearMonthDay2);
        }
        return nums;
    }

    /**
     * day\month\year
     **/
    public static int[] getDayOfMonthYearRelative(int offset) {
        int[] dayMonthYear = new int[3];
        Calendar cal = Calendar.getInstance();
        // 当前年
        int y = cal.get(Calendar.YEAR);
        // 当前月
        int m = (cal.get(Calendar.MONTH)) + 1;//month从0开始
        // 当前月的第几天：即当前日
        int d = cal.get(Calendar.DATE);
        int d_o_m = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        int day1 = offset + d;
        int month1 = m;
        while (day1 <= 0) {
            day1 += getLastDayOfMonth(y, month1 - 1);
            month1--;
        }
        while (day1 > d_o_m) {
            day1 -= getLastDayOfMonth(y, month1);
            month1++;
        }
        while (month1 > 12) {
            month1 -= 12;
            y++;
        }
        while (month1 < 1) {
            month1 += 12;
            y--;
        }
        dayMonthYear[0] = y;
        dayMonthYear[1] = month1;
        dayMonthYear[2] = day1;
        return dayMonthYear;
    }

    /**
     * 计算某个月的最后一天
     **/
    public static int getLastDayOfMonth(int year, int month) {
        Calendar previousCal = Calendar.getInstance();
        previousCal.clear();
        previousCal.set(year, month, 1);//month从0开始
        previousCal.add(Calendar.DAY_OF_MONTH, -1);//下个月1号-1天就是
        return previousCal.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * year\month\day
     **/
    public static int[] getMonthOfYearRelative(int offset) {
        int[] dayMonth = new int[3];
        Calendar cal = Calendar.getInstance();
        // 当前年
        int y = cal.get(Calendar.YEAR);
        // 当前月
        int m = (cal.get(Calendar.MONTH)) + 1;//month从0开始
        int month1 = offset + m;
        while (month1 > 12) {
            month1 -= 12;
            y++;
        }
        while (month1 < 1) {
            month1 += 12;
            y--;
        }
        dayMonth[0] = y;
        dayMonth[1] = month1;
        dayMonth[2] = -1;
        return dayMonth;
    }


    public static int[] getYearRelative(int offset) {
        int[] dayMonthYear = new int[3];
        Calendar cal = Calendar.getInstance();
        // 当前年
        int y = cal.get(Calendar.YEAR);
        int year1 = offset + y;
        dayMonthYear[0] = year1;
        dayMonthYear[1] = -1;
        dayMonthYear[2] = -1;
        return dayMonthYear;
    }

    /**
     * 从形如2014-08-01的格式的字符串中得到int[]，只支持yyyy-MM-dd,yyyy-MM,yyyy三种形式的String
     */
    public static int[] getDateFromText(String dateText) {
        int[] dateArray = null;
        if (!dateText.contains("-")) { //只有年
            dateArray = new int[1];
            dateArray[0] = Integer.valueOf(dateText.substring(0, dateText.length()));
        } else {
            if (dateText.contains("-") && dateText.indexOf("-") != dateText.lastIndexOf("-")) {///有日
                dateArray = new int[3];
                dateArray[0] = Integer.valueOf(dateText.substring(0, dateText.indexOf("-")));
                dateArray[1] = Integer.valueOf(dateText.substring(dateText.indexOf("-") + 1, dateText.lastIndexOf("-")));
                dateArray[2] = Integer.valueOf(dateText.substring(dateText.lastIndexOf("-") + 1, dateText.length()));
            } else if (dateText.contains("-")) {//只有年月
                dateArray = new int[2];
                dateArray[0] = Integer.valueOf(dateText.substring(0, dateText.indexOf("-")));
                dateArray[1] = Integer.valueOf(dateText.substring(dateText.lastIndexOf("-") + 1, dateText.length()));
            }
        }
        return dateArray;
    }

    /**
     * 返回yyyy-MM-dd格式的字符串数组
     * 暂时只支持以下形式：
     * 2015-10-02 年月日
     * 2015-10 年月
     * 2015 年
     * 以后可以加入对半年、季度和周的解析
     **/
    public static String[] getDurationTimes(String time) {
        String[] times = new String[2];
        if (time.matches("\\d{4}\\-\\d{2}$")) {//形如2015-10
            times[0] = time + "-" + "01";
            int[] dateArray = getDateFromText(time);
            times[1] = time + "-" + getLastDayOfMonth(dateArray[0], dateArray[1]);
        } else if (time.matches("\\d{4}$")) {//形如2015,从01-01到12-01
            times[0] = time + "-" + "01" + "-" + "01";
            times[1] = time + "-" + "12" + "-" + "31";
        } else {//形如2015-10-02
            times[0] = time;
            times[1] = time;
        }
        return times;
    }

    /**
     * 将String型格式化,比如想要将2011-11-11格式化成2011年11月11日,就StringPattern("2011-11-11","yyyy-MM-dd","yyyy年MM月dd日").
     *
     * @param date       String 想要格式化的日期
     * @param oldPattern String 想要格式化的日期的现有格式
     * @param newPattern String 想要格式化成什么格式
     * @return String
     */
    public static String StringPattern(String date, String oldPattern, String newPattern) {
        if (date == null || oldPattern == null || newPattern == null)
            return "";
        SimpleDateFormat sdf1 = new SimpleDateFormat(oldPattern, Locale.getDefault());        // 实例化模板对象
        SimpleDateFormat sdf2 = new SimpleDateFormat(newPattern, Locale.getDefault());        // 实例化模板对象
        Date d = null;
        try {
            d = sdf1.parse(date);   // 将给定的字符串中的日期提取出来
        } catch (Exception e) {            // 如果提供的字符串格式有错误，则进行异常处理
            e.printStackTrace();       // 打印异常信息
        }
        return sdf2.format(d);
    }

    /**
     * 格式化时间
     *
     * @param time string
     * @return yyyy-MM-dd HH:mm
     */
    public static String formatDateTime(String time) {

        SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

        if (time == null || "".equals(time)) {
            return "";
        }
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar current = Calendar.getInstance();

        Calendar today = Calendar.getInstance(); // 今天

        today.set(Calendar.YEAR, current.get(Calendar.YEAR));
        today.set(Calendar.MONTH, current.get(Calendar.MONTH));
        today.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH));
        // Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        // today.set(Calendar.SECOND, 0);

        Calendar yesterday = Calendar.getInstance(); // 昨天

        yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
        yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
        yesterday.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 1);
        yesterday.set(Calendar.HOUR_OF_DAY, 0);
        yesterday.set(Calendar.MINUTE, 0);
        // yesterday.set(Calendar.SECOND, 0);

        current.setTime(date);

        if (current.after(today)) {
            return time.split(" ")[1];
        } else if (current.before(today) && current.after(yesterday)) {
            return "昨天" + time.split(" ")[1];
        } else {
            int index = time.indexOf("-") + 1;
            return time.substring(index, time.length());
        }
    }

    /**
     * 判断某一天是否在指定的时间区间内
     */
    public static Boolean isInTimeInterval(String current, String beginTime, String endTime) {
        Boolean result = false;
        Date currentDate;
        Date beginDate;
        Date endDate;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            currentDate = format.parse(current);
            beginDate = format.parse(beginTime);
            endDate = format.parse(endTime);
            if (currentDate.getTime() >= beginDate.getTime() && (currentDate.getTime() <= endDate.getTime())) {
                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取日期格式
     * 暂时只支持以下形式：
     * 2015-10-02 (年月日)
     * 2015-10 (年月)
     * 2015 (年)
     **/
    public static String getDatePattern(String date) {
        if (date.matches("\\d{4}\\-\\d{2}-\\d{2}$")) {//形如2015-10-01
            return "yyyy-MM-dd";
        } else if (date.matches("\\d{4}\\-\\d{2}$")) {//形如2015-10
            return "yyyy-MM";
        } else if (date.matches("\\d{4}$")) {//形如2015
            return "yyyy";
        } else {
            return "";
        }
    }

    /**
     * 比较两个日期的大小，默认返回true,date1小于date2
     * 暂时只支持以下日期形式：
     * 2015-10-02 年月日
     * 2015-10 年月
     * 2015 年
     */
    public static boolean compareDate(String date1, String date2) {
        if (StringUtil.isNotBlank(date1) && StringUtil.isNotBlank(date2)) {
            String pattern1 = getDatePattern(date1);
            String pattern2 = getDatePattern(date2);
            if (StringUtil.isNotBlank(pattern1) && StringUtil.isNotBlank(pattern2)) {
                if (pattern1.equals(pattern2)) {// 日期格式相等
                    SimpleDateFormat sdf = new SimpleDateFormat(getDatePattern(date1), Locale.getDefault());        //将字符串形式的时间转化为Date类型的时间
                    Date a, b;
                    try {
                        a = sdf.parse(date1);
                        b = sdf.parse(date2);
                        return a.before(b);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return false;
    }

    /**
     * 根据日期时间段[2015-01,2015-03]
     * 转化为时间段[2015-01-01,2015-03-31]
     * 参数只支持yyyy-MM的日期格式
     **/
    public static String[] getDateComplete(String[] date) {
        String[] resultDates = new String[2];
        if (date[0].matches("\\d{4}\\-\\d{2}$")) {//形如2015-10
            resultDates[0] = date[0] + "-" + "01";
            int[] dateArray = getDateFromText(date[1]);
            resultDates[1] = date[1] + "-" + getLastDayOfMonth(dateArray[0], dateArray[1]);
        } else {
            resultDates = date;
        }
        return resultDates;
    }
}
